package com.zige.zige.activity.main;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.zige.zige.R;
import com.zige.zige.activity.ActivityVideoWebActivirt;
import com.zige.zige.activity.videoplay.MenuVideodetailActivity;
import com.zige.zige.activity.videoplay.PlayerAvtivity;
import com.zige.zige.bj_vr.BJVrPlayActivity;
import com.zige.zige.bj_vr.BJVrVideoDetailActivity;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.pojo.VideoInfo;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.NetworkUtils;
import com.zige.zige.utils.SharedPreferencesUtils;
import com.zige.zige.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Fei on 2016/2/27.
 */
public class BeforeYesterdayFragment extends Fragment implements View.OnClickListener{



    /**
     * 主页
     */
    private TextView video_title;//视频标题
    private TextView video_content;//视频详情
    private ImageView bg_video;//视频分类标志
    private ViewPager viewPager;
    private MyVPAdapter myVPAdapter;


    private Context context;

    private ArrayList<VideoInfo> mList = new ArrayList<>();

    private MediaPlayer voicePlayer = new MediaPlayer();
    private boolean isPlayVoice = true;
    private  View root;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
         root = inflater.inflate(R.layout.fragment_beforeyesterday, container, false);
        context = getActivity();
        if(NetworkUtils.isNetworkAvailable(context)){
            getHistoryDate("2");
        }else {
            ToastUtils.showToast(context,"当前网络异常");
        }
        initTab();
        initViewPager();
        return root;
    }

    /**
     * 初始化tablayout
     */
    private void initTab() {
        video_title = (TextView) root.findViewById (R.id.tv_video_title);
        video_content = (TextView) root.findViewById (R.id.tv_video_content);
        video_content.setOnClickListener(this);
        bg_video = (ImageView) root.findViewById  (R.id.bg_video_select);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_video_content:
                if (voicePlayer != null) {
                    voicePlayer.pause();
                }
                if(mList.size()>0){
                    if (mList.get(viewPager.getCurrentItem()).getType() == 0) {
                        if (mList.get(viewPager.getCurrentItem()).getActivityType() == 0) {
                            String activityName = mList.get(viewPager.getCurrentItem()).getActivityName();
                            String activityUrl = mList.get(viewPager.getCurrentItem()).getPageUrl();
                            Intent intent = new Intent(context, ActivityVideoWebActivirt.class);
                            intent.putExtra("activityName", activityName);
                            intent.putExtra("activityUrl", activityUrl);
                            startActivity(intent);
                        } else if (mList.get(viewPager.getCurrentItem()).getActivityType() == 1) {
                            Intent intent = new Intent(context, BJVrVideoDetailActivity.class);
                            intent.putExtra("position", viewPager.getCurrentItem());
                            intent.putExtra("activityVideoId", mList.get(viewPager.getCurrentItem()).getId());
                            intent.putExtra("playList", mList);
                            startActivity(intent);
                        }
                    } else if (mList.get(viewPager.getCurrentItem()).getType() == 1) {
                        Intent intent = new Intent(context, MenuVideodetailActivity.class);
                        intent.putExtra("position", viewPager.getCurrentItem());
                        intent.putExtra("playList", mList);
                        intent.putExtra("mList", 0);
                        startActivity(intent);
                    }
                }
                break;
        }
    }

    private void initViewPager() {
        setvideoText(0);

        viewPager = (ViewPager)root.findViewById (R.id.beforyesterday_viewpager);
        setvideoText(0);

        myVPAdapter = new MyVPAdapter();
        viewPager.setAdapter(myVPAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setvideoText(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setOffscreenPageLimit(2);
        viewPager.setCurrentItem(0);
        viewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.page_margin));
    }


    class MyVPAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return (view == object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.home_item_fragment, null);
            ImageView show_video_img = (ImageView) view.findViewById(R.id.home_item_video_pic);
            ImageView playVideo_img = (ImageView) view.findViewById(R.id.play_img);

            show_video_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            });
            if (mList.get(position).getType() == 0) {
                Picasso.with(getActivity()).load(mList.get(position).getPicUrl()).into(show_video_img);
            } else {
                Picasso.with(getActivity()).load(mList.get(position).getVideoPicUrl()).into(show_video_img);
            }
            if (mList.get(position).getType() == 0) {
                if (mList.get(position).getActivityType() == 0) {
                    playVideo_img.setVisibility(View.GONE);
                    show_video_img.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (voicePlayer != null) {
                                voicePlayer.pause();
                            }
                            String activityName = mList.get(position).getActivityName();
                            String activityUrl = mList.get(position).getPageUrl();
                            Intent intent = new Intent(getActivity(), ActivityVideoWebActivirt.class);
                            intent.putExtra("activityName", activityName);
                            intent.putExtra("activityUrl", activityUrl);
                            startActivity(intent);
                        }
                    });
                } else if (mList.get(position).getActivityType() == 1) {
                    playVideo_img.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (voicePlayer != null) {
                                voicePlayer.pause();
                            }
                            Intent intent = new Intent(getActivity(), BJVrPlayActivity.class);
                            intent.putExtra("position", position);
                            intent.putExtra("activityVideoId", mList.get(position).getId());
                            intent.putExtra("playList", mList);
                            startActivity(intent);
                        }

                    });
                }
            } else if (mList.get(position).getType() == 1) {
                playVideo_img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (voicePlayer != null) {
                            voicePlayer.pause();
                        }
                        Intent intent = new Intent(getActivity(), PlayerAvtivity.class);
                        intent.putExtra("position", position);
                        intent.putExtra("playList", mList);
                        startActivity(intent);
                    }
                });
            }
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            View view = (View) object;
            container.removeView(view);
        }
    }



    private void getHistoryDate(String day) {
        HashMap<String, String> params = new HashMap<>();
        params.put("dayIndex", day);
        params.put("account", "");
        TaskExecutor.getInstance().execute(new PostRequestTask(params, getActivity(), UrlConsts.USER_WATCH_HOISTORY) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    String msg = object.getString("message");
                    if (code == 0000) {
                        JSONArray videoArray = object.getJSONArray("videoBaseVOList");
                        if (videoArray != null && videoArray.length() > 0)
                            for (int i = 0; i < videoArray.length(); i++) {
                                JSONObject jsonObject = videoArray.getJSONObject(i);
                                VideoInfo item = new VideoInfo();
                                item.setType(1);
                                item.setId(jsonObject.getString("vid"));
                                item.setVideoName(jsonObject.getString("videoName"));
                                item.setVideoDesc(jsonObject.getString("themeDesc"));
                                item.setVideoDesc(jsonObject.getString("videoDesc"));
                                item.setVideoPicUrl(jsonObject.getString("videoPicUrl"));
                                item.setVideoUrl(jsonObject.getString("videoUrl"));
                                item.setVideoTypeName(jsonObject.getString("themeName"));
                                item.setThemeVoiceUrl(jsonObject.getString("themeVoiceUrl"));
                                item.setpraiseUserids(jsonObject.getString("praiseUserids"));
                                // item.setVideoUrl(obj.getString("videoUrl"));
                                mList.add(item);
                            }
                        setvideoText(0);
                        myVPAdapter.notifyDataSetChanged();
                    } else {
                        throw new Exception(msg);
                    }
                } catch (Exception e) {
                    ToastUtils.showToast(getContext(), e.getMessage());
                } finally {
                }
            }
        });
    }




    private void setvideoText(int position) {
        if (mList.size() > 0) {
            if (mList.get(position).getType() == 0) {
                if (mList.get(position).getActivityType() == 0) {
                    bg_video.setImageResource(R.drawable.video_bg_img);
                } else {
                    bg_video.setImageResource(R.drawable.vr_bg_img);
                }
                video_title.setText(mList.get(position).getActivityName());
                video_content.setText(mList.get(position).getVideoDesc());
            } else {
                bg_video.setImageResource(R.drawable.video_bg_img);
                video_title.setText(mList.get(position).getVideoName());
                video_content.setText(mList.get(position).getVideoDesc());
            }
            palyVoide(position);
        }
    }

    /*
   播放音频
    */
    private boolean isVoiceLoad;
    private void palyVoide(int position) {
        isPlayVoice = (boolean) SharedPreferencesUtils.getValue(getActivity(), SharedPreferencesUtils.isplayvoice, true);
        isVoiceLoad = (boolean)SharedPreferencesUtils.getValue(getActivity(),SharedPreferencesUtils.voice_loading,false);
        if (voicePlayer != null) {

            voicePlayer.release();
            voicePlayer = null;
            voicePlayer = new MediaPlayer();
        } else {
            voicePlayer = new MediaPlayer();
        }
        voicePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if (voicePlayer != null && !isPlayVoice &&isVoiceLoad) {
                    voicePlayer.start();
                } else {
                    voicePlayer.pause();
                }
            }
        });
        try {
            String voiceURL = mList.get(position).getThemeVoiceUrl();
            if (voiceURL != null && voiceURL != "") {
                voicePlayer.setDataSource(voiceURL);
                voicePlayer.prepareAsync();
            }
        } catch (Exception ex) {
            Toast toast = Toast.makeText(getContext(), "Error Playing Sound:" + ex.toString(), Toast.LENGTH_SHORT);
            toast.show();
        }
    }



}
